<?php

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;        //导入上传类
//use Qiniu\Processing\PersistentFop;     //导入持久化转码类
//use Qiniu\Storage\BucketManager;
class Qiniu{

    private $accessKey;
    private $secretKey;
    private $cname;
    private $bucket;

    public function __construct($qiniu)
    {
        require_once __DIR__ . '/qiniu/autoload.php';
        $this->accessKey = $qiniu['accessKey'];//'vZQ9iHKpx5w6Jc0707XPsBzNCOdnDs3t50KWzfRe';
        $this->secretKey = $qiniu['secretKey'];
        $this->cname = $qiniu['cname'];//'idv093d.qiniudns.com';
        $this->bucket = $qiniu['bucket'];

    }


    //获取七牛的token
    public function get_token(){
        $auth = new Auth($this->accessKey, $this->secretKey);
        $token = $auth->uploadToken($this->bucket);
        return $token;
    }


    /**
     * @param $file_tmp 临时文件地址
     * @param $type 文件的后缀
     * @throws Exception
     */
    public function upload($file_tmp,$key){
        $expires = 6000;
        $auth = new Auth($this->accessKey, $this->secretKey);
        $token = $auth->uploadToken($this->bucket);
        $uploadMgr = new UploadManager();
        // 要上传文件的本地路径
        // 上传到七牛后保存的文件名
        //$key="/images/".time().rand(1000000,9999999).'.'.$type;
        list($ret, $err) = $uploadMgr->putFile($token, $key, $file_tmp);
        if ($err !== null) {
            return ['code'=>false,'data'=>'图片上传失败'];
        } else {
            $ima_path='http://qn.enshitc.com/'.$ret['key'];
            return ['code'=>true,'data'=>$ima_path];
        }
    }


    /**
     * 删除七牛上面的图片资源
     */
    public function qiniu_del($key){
        $auth = new QIAuth($this->accessKey, $this->secretKey);
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($auth, $config);
        $err = $bucketManager->delete($this->bucket, $key);
        if ($err) {
            dump($err);
            echo "文件删除失败";
        }else{
            echo "删除文件成功";die();
        }
    }


}
